package javaapplication1;

import java.io.*;
import java.net.*;


public class Network {
        Game game;
	Socket requestSocket;
	ObjectOutputStream out;
 	ObjectInputStream in;

        // constructor
        Network (Game game) {
            this.game = game;
        }


        // “Tells” to the server that given robot attacking specified wall section. 
        public void attack(int robot, int wall, int section) {
            String message;
            message = "AT; A" + game.get_myNum() + "," + robot + "; " +
                        wall + "," + section + "; " +
                        game.get_OurRobots(robot).get_power();
            sendMessage(message);
        }

        // “Tells” server that user is moving given robot to specified place
        public void move(int robot, int x, int y) {
            String message;
            message = "MV; A" + game.get_myNum() + "," + robot + "; " +
                        x + "," + y;
            sendMessage(message);
        }

        // Sends chat message
        //isPri is 0 for public, 1 for private
        public void sendChatMsg(String msg, boolean isPri) {
            String message = "MSG; ";
            if (isPri) message = message + "PRI; ";
            else message = message + "PUB; ";
            message = message + "ATT; " + msg;
            sendMessage(message);   
        }

        // sends message to the server
 	private void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}

        // Establishes connection with the server
	public void connect() {
                Listener listener;
		try {
			//1. creating a socket to connect to the server
			requestSocket = new Socket("192.249.29.61", 2004);
			System.out.println("Connected to localhost in port 2004");
			//2. get Input and Output streams
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());

                        listener = new Listener(in);
                        Thread t = new Thread(listener);
                        t.start();
		} 
		catch(UnknownHostException unknownHost){
			System.err.println("You are trying to connect to an unknown host!");
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
		finally{
			//4: Closing connection
			try{
				in.close();
				out.close();
				requestSocket.close();
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
	}

}
